# -*- coding: utf-8 -*-
'''
| @author: olivia.dou
| Created on: 2019/7/3 6:49
| desc: text_sum算法输出结果验证
'''

import unittest, json, os
import pandas as pd
from jsonpath import jsonpath
from jsonschema import validate,ValidationError
import requests
import base.globalvars as glo
from base.ddt import ddt, data

dataset = []

@ddt
class TestTextSum(unittest.TestCase):
    datafile = glo.get_value("algo_paths_map")['text_sum']['Data_File']
    schemafile = glo.get_value("algo_paths_map")['text_sum']['Schema_File']
    baseline_data = pd.read_csv(os.path.split(__file__)[0] + os.sep + datafile,
                                encoding='gb18030',dtype=str)  # 为在Excel中打开时不是乱码，使用gb2312
    baseline_data.apply(lambda x: dataset.append(x.to_dict()), axis=1)

    @classmethod
    def setUpClass(cls):
        algo_name = glo.get_value("algo_paths_map")['text_sum']['Algo_Name']
        host1 = glo.get_value("algo_paths_map")['text_sum']['Host']
        port1 = glo.get_value("algo_paths_map")['text_sum']['Port']

        cls.url = "http://" + host1 + ':' + str(port1) + '/algorithm/process/' + algo_name

    @data(*dataset)
    def testSchema(self, testdata):
        testdata['content'] = testdata['content'].replace('????','    ') # 恢复连续空格在csv中的乱码

        parameter = {'title': testdata['title'], 'content': testdata['content']}
        self.payload = {'parameter': json.dumps(parameter, ensure_ascii=False)}
        self.response = requests.post(self.url, data=self.payload)
        self.assertTrue(self.response.status_code == 200, "status code:%s" % self.response.status_code)
        self.assertTrue(jsonpath(self.response.json(), "$.stat") == [0],
                        "text_sum request format invalid: %s" % jsonpath(self.response.json(), "$.message"))


        try:
            schema = json.load(open(os.path.split(__file__)[0] + os.sep +self.schemafile))
            validate(instance=self.response.json(), schema=schema)
        except ValidationError as e:
            self.fail("Request not successful: %s"%e)








 